﻿//Get query string param value
$.extend({
    getQueryStringValue: function (paramName) {
        /// <summary>
        ///     Get the value of input parameter from the querystring
        /// </summary>
        /// <param name="paramName" type="String">The input parameter whose value is to be extracted</param>
        /// <returns type="String">The value of input parameter from the querystring</returns>

        parName = paramName.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
        var pattern = '[\\?&]' + paramName + '=([^&#]*)';
        var regex = new RegExp(pattern);
        var matches = regex.exec(window.location.href);
        if (matches == null) return '';
        else return decodeURIComponent(matches[1].replace(/\+/g, ' '));
    }
});

//Global growl settings
$.extend($.gritter.options, {
    position: 'top-left', // defaults to 'top-right' but can be 'bottom-left', 'bottom-right', 'top-left', 'top-right' (added in 1.7.1)
    fade_in_speed: 500, // how fast notifications fade in (string or int)
    fade_out_speed: 1000, // how fast the notices fade out
    time: 5000 // hang on the screen for...
});

//Static type for growl message
function GrowlType() { };
GrowlType.ERROR = -1;
GrowlType.SUCCESS = 0;
GrowlType.INFO = 1;
GrowlType.WARNING = 2;
//Growl message extend
$.extend({
    showGrowlMessage: function (type, message) {

        var growlId = $.gritter.add({
            // (string | mandatory) the heading of the notification
            title: 'I am to be replaced :)',
            // (string | mandatory) the text inside the notification
            text: message
        });

        //Get the title of the growl message
        var growlTitle = $('#gritter-item-' + growlId.toString() + ' .gritter-title');

        switch (type) {
            case GrowlType.ERROR:
                growlTitle.text('Error!').css('color', 'red');
                break;
            case GrowlType.SUCCESS:
                growlTitle.text('Ok!').css('color', 'lightgreen');
                break;
            case GrowlType.INFO:
                growlTitle.text('Info:').css('color', 'white');
                break;
            case GrowlType.WARNING:
                growlTitle.text('Warning:').css('color', 'yellow');
                break;
        }
    }
});

//Growl sticky message extend
$.extend({
    showHelpMessage: function (message) {
        //Get multiple parts message
        var messages = message.split('|');
        //Build the help list
        var finalMsgList = '<ul style="margin-left:20px">';
        for (var i = 0; i < messages.length; i++) {
            finalMsgList += '<li>' + messages[i] + '</li>';
        }
        finalMsgList += '</ul>';
        //Then show the sticky growl
        $.gritter.add({
            // (string | mandatory) the heading of the notification
            title: 'Help',
            // (string | mandatory) the text inside the notification
            text: finalMsgList,
            sticky: true
        });
    }
});

//Whole screen block
$.extend({
    showLoading: function () {
        $.blockUI({
            message: "",
            css:
            {
                backgroundColor: 'transparent',
                border: 0,
                cursor: 'wait'
            },
            overlayCSS:
            {
                backgroundColor: '#000',
                opacity: 0.2
            }
        });
    }
});


///////////////////////////////////////////////////
//               Custom plugins                  //
///////////////////////////////////////////////////
(function ($) {
    //Toggle required textbox mode
    $.fn.requiredModeOn = function () {
        this.animate({
            backgroundColor: "#FFA0A0",
            borderTopColor: "#FF3030",
            borderLeftColor: "#FF3030",
            borderRightColor: "#FF3030",
            borderBottomColor: "#FF3030"
        }, 500);
    };

    $.fn.requiredModeOff = function () {
        this.animate({
            backgroundColor: "#FFFFFF",
            borderTopColor: "#999999",
            borderLeftColor: "#999999",
            borderRightColor: "#999999",
            borderBottomColor: "#999999"
        }, 500);
    }

    //Fade in text
    $.fn.fadeInText = function (message) {
        this.text(message.toString());
        this.stop().fadeIn("normal");
    }
    //Fade in text
    $.fn.fadeInText = function (message) {
        this.text(message.toString());
        this.stop().fadeIn("normal");
    }

    //Block the div and show loading message
    $.fn.showLoading = function () {
        this.block({
            message: "<div class='blockIcon'></div>",
            css:
            {
                width: '70px',
                textAlign: 'center',
                backgroundColor: 'transparent',
                border: 0,
                cursor: 'wait'
            },
            overlayCSS:
            {
                backgroundColor: '#000',
                opacity: 0.2
            }
        });
    }

    //Unblock the div
    $.fn.hideLoading = function () {
        this.unblock();
    }

    //jQueryUI Combo box
    $.widget( "ui.combobox", {
			_create: function() {
				var self = this,
					select = this.element.hide(),
					selected = select.children( ":selected" ),
					value = selected.val() ? selected.text() : "";
				var input = this.input = $( "<input>" )
					.insertAfter( select )
					.val( value )
					.autocomplete({
						delay: 0,
						minLength: 0,
						source: function( request, response ) {
							var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
							response( select.children( "option" ).map(function() {
								var text = $( this ).text();
								if ( this.value && ( !request.term || matcher.test(text) ) )
									return {
										label: text.replace(
											new RegExp(
												"(?![^&;]+;)(?!<[^<>]*)(" +
												$.ui.autocomplete.escapeRegex(request.term) +
												")(?![^<>]*>)(?![^&;]+;)", "gi"
											), "<strong>$1</strong>" ),
										value: text,
										option: this
									};
							}) );
						},
						select: function( event, ui ) {
							ui.item.option.selected = true;
							self._trigger( "selected", event, {
								item: ui.item.option
							});
						},
						change: function( event, ui ) {
							if ( !ui.item ) {
								var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
									valid = false;
								select.children( "option" ).each(function() {
									if ( $( this ).text().match( matcher ) ) {
										this.selected = valid = true;
										return false;
									}
								});
								if ( !valid ) {
									// remove invalid value, as it didn't match anything
									$( this ).val( "" );
									select.val( "" );
									input.data( "autocomplete" ).term = "";
									return false;
								}
							}
						}
					})
					.addClass( "ui-corner-left" );

				input.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li></li>" )
						.data( "item.autocomplete", item )
						.append( "<a>" + item.label + "</a>" )
						.appendTo( ul );
				};

				this.button = $( "<button type='button'>&nbsp;</button>" )
					.attr( "tabIndex", -1 )
					.attr( "title", "Show All Items" )
					.insertAfter( input )
					.button({
						icons: {
							primary: "ui-icon-triangle-1-s"
						},
						text: false
					})
					.removeClass( "ui-corner-all" )
					.addClass( "ui-corner-right ui-button-icon" )
					.click(function() {
						// close if already visible
						if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
							input.autocomplete( "close" );
							return;
						}

						// work around a bug (likely same cause as #5265)
						$( this ).blur();

						// pass empty string as value to search for, displaying all results
						input.autocomplete( "search", "" );
						input.focus();
					});
			},

			destroy: function() {
				this.input.remove();
				this.button.remove();
				this.element.show();
				$.Widget.prototype.destroy.call( this );
			}
    });
})(jQuery);


$(document).keyup(function(e){
    if (e.keyCode == 27) {
        window.location = 'Default.aspx';
    }
});